<template>
  <div class="lifesignDetail">
    <el-row class="lifesignDetail-a height40">
      <span class="height40-span">
        <img :src="image.juxing_Small" alt />
      </span>
      <span class="height40-span">{{roomGeneralViewManagement.vitalSignsViewDetail}}</span>
    </el-row>
    <el-row class="lifesignDetail-b">
      <!-- 心跳 -->
      <div id="chartLine" ref="chartLine" style="width:98%;height:400px;"></div>
      <!-- 呼吸 -->
      <div id="chartLine2" ref="chartLine2" style="width:98%;height:400px;"></div>
    </el-row>
    <el-row class="lifesignDetail-c">
      <kt-button
        class="btn boxShadowButton"
        :label="roomGeneralViewManagement.backList"
        @click="handleBack"
      />
    </el-row>
  </div>
</template>
<script>
import echarts from "echarts";
import KtButton from "@/components/KtButton";
import bus from "../../../vuex/eventBus"; //引入eventBus,接收子界面传递的跳转指令,然后在父界面跳转,添加tab
import juxing_Small from "../../../assets/lifeGroupimg/juxing_small.png";
import mqtt from "mqtt"; //导入mqtt
import {
  MQTT_SERVICE,
  MQTT_USERNAME,
  MQTT_PASSWORD,
  MQTT_CLIENTID
} from "../../../api/http.js";
import util from "@/commons/js/util.js";
export default {
  name: "LifesignDetail",
  data() {
    return {
      roomGeneralViewManagement: this.$t("m.roomGeneralViewManagement"), //引入 lang 里面的字符串资源,
      size: "medium", //按钮的尺寸
      image: { juxing_Small },
      msg: "", //mqtt推送的消息
      deviceNo: "", //设备编号
      heartbeat_sginal: [],
      heartbeat_max: [],
      heartbeat_min: [],
      heartbeat_time: [],
      breathe_sginal: [],
      breathe_max: [],
      breathe_min: [],
      breathe_time: [],
      flag: false, //页面进来为false 需要请求数据 获取曲线图的数据
      acceptLanguage: "ja_JP", //数据请求传参需要传的语言  ja_JP----日文
      options: {
        connectTImeout: 4000, //超时连接的时间
        clientId: MQTT_CLIENTID,
        //clientId: "mqtitId-" + new Date().getTime(),
        //clientId: 'mqtitId-Home',
        username: MQTT_USERNAME,
        password: MQTT_PASSWORD,
        clean: true
      },
      client: ""
    };
  },
  methods: {
    /* 
      返回上传
    */
    handleBack() {
      bus.$emit("homePage", {
        type: "remove",
        path: "/LifesignDetail",
        showpath: "/RoomGeneralViewDetail"
      });
    },

    /* 
      心跳
    */
    drawLineChartHeartbeat() {
      var myChartLine = this.$refs.chartLine;
      console.log(myChartLine, "-------", echarts);
      if (myChartLine) {
        let chartLine = echarts.init(myChartLine);
        chartLine.setOption({
          animation: false, //animation为true是有渲染数据的动画,animation为false没有渲染数据的动画
          title: {
            text: ""
          },
          tooltip: {
            trigger: "axis"
          },
          legend: {
            data: [this.roomGeneralViewManagement.heartbeat]
          },
          color: ["#4462ff", "#ff3336", "chartreuse"],
          grid: {
            top: "10%",
            left: "5%",
            right: "4%",
            bottom: "3%",
            containLabel: true
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            name: this.roomGeneralViewManagement.time,
            data: []
          },
          yAxis: {
            type: "value",
            name: this.roomGeneralViewManagement.heartbeat
          },
          series: [
            {
              name: this.roomGeneralViewManagement.heartbeat,
              type: "line",
              symbol: "circle", // 拐点类型
              smooth: true, // 当为true时，就是光滑的曲线（默认为true）；当为false，就是折线不是曲线的了，那这个设为true，下面的（吃饭）数据中设置smooth为false，这个就不是光滑的曲线了。
              symbolSize: 3, // 拐点圆的大小
              itemStyle: {
                normal: {
                  //color: "#1E90FF", // 折线条的颜色
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: "#d7f4f8" // 0% 处的颜色
                    },
                    {
                      offset: 0,
                      color: "#37abc0" // 25% 处的颜色
                    },
                    {
                      offset: 0.5,
                      color: "#eefcfd" // 50% 处的颜色
                    },
                    {
                      offset: 0.75,
                      color: "#d7f4f8" // 75% 处的颜色
                    },
                    {
                      offset: 1,
                      color: "#4437c0" // 100% 处的颜色
                    }
                  ]), //背景渐变色
                  lineStyle: {
                    // 系列级个性化折线样式
                    width: 3,
                    type: "solid",
                    color: "#4fd6d2"
                  },
                  borderColor: "#1E90FF" // 拐点边框颜色
                },
                emphasis: {
                  color: "#4fd6d2",
                  lineStyle: {
                    // 系列级个性化折线样式
                    width: 2,
                    type: "dotted",
                    color: "#4fd6d2" //折线的颜色
                  }
                }
              },
              symbolSize: 5, //折线点的大小
              areaStyle: { normal: {} }, //渐变区域
              data: []
            },
            {
              name: this.roomGeneralViewManagement.heartbeat,
              type: "line",
              symbol: "circle", // 拐点类型
              smooth: true, // 当为true时，就是光滑的曲线（默认为true）；当为false，就是折线不是曲线的了，那这个设为true，下面的（吃饭）数据中设置smooth为false，这个就不是光滑的曲线了。
              symbolSize: 3, // 拐点圆的大小
              itemStyle: {
                normal: {
                  //color: "#1E90FF", // 折线条的颜色
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: "#d7f4f8" // 0% 处的颜色
                    },
                    {
                      offset: 0,
                      color: "#37abc0" // 25% 处的颜色
                    },
                    {
                      offset: 0.5,
                      color: "#eefcfd" // 50% 处的颜色
                    },
                    {
                      offset: 0.75,
                      color: "#d7f4f8" // 75% 处的颜色
                    },
                    {
                      offset: 1,
                      color: "#4437c0" // 100% 处的颜色
                    }
                  ]), //背景渐变色
                  lineStyle: {
                    // 系列级个性化折线样式
                    width: 3,
                    type: "solid",
                    color: "#4fd6d2"
                  },
                  borderColor: "#1E90FF" // 拐点边框颜色
                },
                emphasis: {
                  color: "#4fd6d2",
                  lineStyle: {
                    // 系列级个性化折线样式
                    width: 2,
                    type: "dotted",
                    color: "#4fd6d2" //折线的颜色
                  }
                }
              },
              symbolSize: 5, //折线点的大小
              areaStyle: { normal: {} },
              data: []
            },
            {
              name: this.roomGeneralViewManagement.heartbeat,
              type: "line",
              symbol: "circle", // 拐点类型
              smooth: true, // 当为true时，就是光滑的曲线（默认为true）；当为false，就是折线不是曲线的了，那这个设为true，下面的（吃饭）数据中设置smooth为false，这个就不是光滑的曲线了。
              symbolSize: 3, // 拐点圆的大小
              itemStyle: {
                normal: {
                  //color: "#1E90FF", // 折线条的颜色
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: "#d7f4f8" // 0% 处的颜色
                    },
                    {
                      offset: 0,
                      color: "#37abc0" // 25% 处的颜色
                    },
                    {
                      offset: 0.5,
                      color: "#eefcfd" // 50% 处的颜色
                    },
                    {
                      offset: 0.75,
                      color: "#d7f4f8" // 75% 处的颜色
                    },
                    {
                      offset: 1,
                      color: "#4437c0" // 100% 处的颜色
                    }
                  ]), //背景渐变色
                  lineStyle: {
                    // 系列级个性化折线样式
                    width: 3,
                    type: "solid",
                    color: "#4fd6d2"
                  },
                  borderColor: "#1E90FF" // 拐点边框颜色
                },
                emphasis: {
                  color: "#4fd6d2",
                  lineStyle: {
                    // 系列级个性化折线样式
                    width: 2,
                    type: "dotted",
                    color: "#4fd6d2" //折线的颜色
                  }
                }
              },
              symbolSize: 5, //折线点的大小
              areaStyle: { normal: {} },
              data: []
            }
          ]
        });
        chartLine.showLoading(); //加载动画、
        if (this.flag == false) {
          //传参 axios发起数据请求
          let params = new Object();
          params.pageNum = 1;
          params.pageSize = 1000;
          params.deviceId = this.bedDeviceId;
          params.smoothFactor = 300;
          params.startQueryTime = util.formatDate.Time(
            new Date(new Date().getTime())
          );
          params.endQueryTime =
            util.formatDate.getNowFormatDate() + " 23:59:59";
          params.step = 60;
          console.log(params);
          this.heartbeat_sginal = [];
          this.heartbeat_max = [];
          this.heartbeat_min = [];
          this.heartbeat_time = [];
          this.$postJson(
            this.ports.roomGeneralViewManagement.lifesignDetail,
            params,
            this.acceptLanguage
          ).then(res => {
            console.log(res);
            if (res.result != null) {
              if (res.result.hr_sginal) {
                this.heartbeat_sginal = res.result.hr_sginal; //输出心跳数组
              }
              // this.heartbeat_max=res.result.hr_max;//输出心跳不确定性上限数组
              // this.heartbeat_min=res.result.hr_min;//输出心跳不确定性下限数组
              if (res.result.signaltime) {
                res.result.signaltime.forEach(item => {
                  //var time = util.formatDate.Time(new Date(item * 1000)); //时间戳需要乘以1000  显示了格式为日期时间格式
                  var time = util.formatDate.format(
                    new Date(item * 1000),
                    "hh:mm:ss"
                  ); //时间戳需要乘以1000   显示为时间格式
                  this.heartbeat_time.push(time);
                });
              }
            }
            console.log(this.heartbeat_time);
            chartLine.hideLoading(); //加载成功关闭动画
            //将后台获取的值注入data中，echaert图形展示获取的数据
            chartLine.setOption({
              xAxis: {
                data: this.heartbeat_time
              },
              series: [
                {
                  name: this.roomGeneralViewManagement.heartbeat,
                  type: "line",
                  data: this.heartbeat_sginal
                },
                {
                  name: "",
                  type: "line",
                  data: this.heartbeat_max
                },
                {
                  name: "",
                  type: "line",
                  data: this.heartbeat_min
                }
              ]
            });
            this.flag = true; //收到消息flag==true
          });
        } else {
          chartLine.hideLoading(); //加载成功关闭动画
          //将后台获取的值注入data中，echaert图形展示获取的数据
          chartLine.setOption({
            xAxis: {
              data: this.heartbeat_time
            },
            series: [
              {
                name: this.roomGeneralViewManagement.heartbeat,
                type: "line",
                data: this.heartbeat_sginal
              },
              {
                name: "",
                type: "line",
                data: this.heartbeat_max
              },
              {
                name: "",
                type: "line",
                data: this.heartbeat_min
              }
            ]
          });
        }
        window.addEventListener("resize", function() {
          //console.log("窗口变化，心跳的echart自适应")
          chartLine.resize(); //重置echart的大小
        });
      }
    },

    /* 
      呼吸
    */
    drawLineChartBreathe() {
      var myChartLine = this.$refs.chartLine2;
      console.log(myChartLine, "-------", echarts);
      if (myChartLine) {
        let chartLine = echarts.init(myChartLine);
        chartLine.setOption({
          animation: false, //animation为true是有渲染数据的动画,animation为false没有渲染数据的动画
          title: {
            text: ""
          },
          tooltip: {
            trigger: "axis"
          },
          legend: {
            data: [this.roomGeneralViewManagement.breathe]
          },
          color: ["#4462ff", "#ff3336", "chartreuse"],
          grid: {
            top: "10%",
            left: "5%",
            right: "4%",
            bottom: "3%",
            containLabel: true
          },
          xAxis: {
            type: "category",
            boundaryGap: false,
            name: this.roomGeneralViewManagement.time,
            data: []
          },
          yAxis: {
            type: "value",
            name: this.roomGeneralViewManagement.breathe
          },
          series: [
            {
              name: this.roomGeneralViewManagement.breathe,
              type: "line",
              symbol: "circle", // 拐点类型  8种类型  默认的有circle/rectangle/triangle/diamond/emptyCircle/emptyRectangle/emptyTriangle/emptyDiamond  还支持5种特别的标志图形：heart(心形)、droplet(水滴)、pin(标注)、arrow(箭头)、star(五角星)
              smooth: true, // 当为true时，就是光滑的曲线（默认为true）；当为false，就是折线不是曲线的了，那这个设为true，下面的（吃饭）数据中设置smooth为false，这个就不是光滑的曲线了。
              symbolSize: 3, // 拐点圆的大小
              itemStyle: {
                normal: {
                  //color: "#1E90FF", // 折线条的颜色
                  //渐变颜色设置
                  color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                    {
                      offset: 0,
                      color: "#5dc745" // 0% 处的颜色
                    },
                    {
                      offset: 0,
                      color: "#aac745" // 25% 处的颜色
                    },
                    {
                      offset: 0.5,
                      color: "#c79e45" // 50% 处的颜色
                    },
                    {
                      offset: 0.75,
                      color: "#c77945" // 75% 处的颜色
                    },
                    {
                      offset: 1,
                      color: "#c76645" // 100% 处的颜色
                    }
                  ]), //背景渐变色
                  lineStyle: {
                    // 系列级个性化折线样式
                    width: 3,
                    type: "solid",
                    color: "#4fd6d2"
                  },
                  borderColor: "#1E90FF" // 拐点边框颜色
                },
                emphasis: {
                  color: "#4fd6d2",
                  lineStyle: {
                    // 系列级个性化折线样式
                    width: 2,
                    type: "dotted",
                    color: "#4fd6d2" //折线的颜色
                  }
                }
              },
              symbolSize: 5, //折线点的大小
              areaStyle: { normal: {} }, //区域渐变颜色
              data: []
            }
          ]
        });
        chartLine.showLoading(); //加载动画
        if (this.flag == false) {
          //传参 axios发起数据请求
          let params = new Object();
          params.pageNum = 1;
          params.pageSize = 1000;
          params.deviceId = this.bedDeviceId;
          params.smoothFactor = 300;
          params.startQueryTime = util.formatDate.Time(
            new Date(new Date().getTime())
          );
          params.endQueryTime =
            util.formatDate.getNowFormatDate() + " 23:59:59";
          params.step = 60;
          this.breathe_sginal = [];
          this.breathe_max = [];
          this.breathe_min = [];
          this.breathe_time = [];
          console.log(params);
          this.$postJson(
            this.ports.roomGeneralViewManagement.lifesignDetail,
            params,
            this.acceptLanguage
          ).then(res => {
            console.log(res);
            if (res.result != null) {
              if (res.result.br_signal) {
                this.breathe_sginal = res.result.br_signal; //输出呼吸数组
              }
              // this.breathe_max=res.result.br_max;//输出呼吸不确定性上限数组
              // this.breathe_min=res.result.br_min;//输出呼吸不确定性下限数组
              if (res.result.signaltime) {
                res.result.signaltime.forEach(item => {
                  //var time = util.formatDate.Time(new Date(item * 1000)); //时间戳需要乘以1000  显示了格式为日期时间格式
                  var time = util.formatDate.format(
                    new Date(item * 1000),
                    "hh:mm:ss"
                  ); //时间戳需要乘以1000 显示的格式为时间格式
                  this.breathe_time.push(time);
                });
              }
            }
            chartLine.hideLoading(); //加载成功关闭动画
            //将后台获取的值注入data中，echaert图形展示获取的数据
            chartLine.setOption({
              xAxis: {
                data: this.breathe_time
              },
              series: [
                {
                  name: this.roomGeneralViewManagement.breathe,
                  type: "line",
                  data: this.breathe_sginal
                },
                {
                  name: "",
                  type: "line",
                  data: this.breathe_max
                },
                {
                  name: "",
                  type: "line",
                  data: this.breathe_min
                }
              ]
            });
          });
        } else {
          chartLine.hideLoading(); //加载成功关闭动画
          //将后台获取的值注入data中，echaert图形展示获取的数据
          chartLine.setOption({
            xAxis: {
              data: this.breathe_time
            },
            series: [
              {
                name: this.roomGeneralViewManagement.breathe,
                type: "line",
                data: this.breathe_sginal
              },
              {
                name: "",
                type: "line",
                data: this.breathe_max
              },
              {
                name: "",
                type: "line",
                data: this.breathe_min
              }
            ]
          });
        }
        window.addEventListener("resize", function() {
          //console.log("窗口变化，呼吸的echart自适应")
          chartLine.resize(); //重置echart的大小
        });
      }
    },

    /* 
      调取echart
    */
    drawCharts() {
      this.drawLineChartHeartbeat();
      this.drawLineChartBreathe();
    },

    /* 
      mqtt
    */
    mqttMSG() {
      this.client = mqtt.connect(MQTT_SERVICE, this.options);
      // mqtt连接
      this.client.on("connect", e => {
        console.log(e);
        console.log("连接成功:");
        let deviceNo = this.deviceNo;
        let topic = "FRONT_CLIENT_" + deviceNo; // deviceNo 是守护佳床垫设备编号
        this.client.subscribe(topic, error => {
          console.log(topic, "topic");
          if (!error) {
            console.log("-----------------gzh: 订阅成功");
          } else {
            console.log("-----------------gzh: 订阅失败");
          }
        });
      });
      // 接收消息处理
      this.client.on("message", (topic, message) => {
        console.log("收到来自", topic, "的消息", message.toString());
        this.msg = message.toString();
        console.log(this.msg);
        this.msg = JSON.parse(this.msg);
        console.log(this.msg);
        //去除心跳和呼吸为-1的数据
        if (this.msg.heartbeat != -1) {
          this.heartbeat_sginal.push(this.msg.heartbeat);
          this.heartbeat_time.push(
            //util.formatDate.Time(new Date(new Date().getTime()))//显示的格式为日期时间格式
            util.formatDate.format(new Date(new Date().getTime()), "hh:mm:ss") //时间戳需要乘以1000  显示的格式为时间格式
          ); //获取系统时间
        }
        if (this.msg.breath != -1) {
          this.breathe_sginal.push(this.msg.breath);
          this.breathe_time.push(
            //util.formatDate.Time(new Date(new Date().getTime()))//显示的格式为日期格式
            util.formatDate.format(new Date(new Date().getTime()), "hh:mm:ss") //时间戳需要乘以1000
          ); //获取系统时间
        }
        this.drawCharts(); //重新调取echarts画图
      });
      // 断开发起重连
      this.client.on("reconnect", error => {
        console.log("正在重连:", error);
      });
      // 链接异常处理
      this.client.on("error", error => {
        console.log("连接失败:", error);
      });
    }
  },
  created() {
    this.deviceNo = sessionStorage.getItem("bedDeviceNo");
    this.bedDeviceId = sessionStorage.getItem("bedDeviceId");
  },
  mounted() {
    this.drawCharts();
    console.log("-----------------gzh: mqtt connect...");
    this.mqttMSG();
    setTimeout(function() {
      bus.$emit("homePage", { type: "add", path: "/LifesignDetail" });
    }, "1000");
  },
  beforeDestroy() {
    console.log('lifesigndetail destoryed()')
    sessionStorage.removeItem("bedDeviceNo");
    sessionStorage.removeItem("bedDeviceId");
    this.client.end(); //断开mqtt的连接  组件销毁后需要断开mqtt的连接 否则后端就会一直推送消息影响性能
  },
  components: {
    KtButton
  }
};
</script>
<style lang="scss" scoped>
.lifesignDetail {
  padding-bottom: 20px;
  .height40 {
    height: 40px;
    line-height: 40px;
    .height40-span {
      display: inline-block;
      height: 40px;
      line-height: 40px;
      font-size: 18px;
      font-weight: 700;
      img {
        vertical-align: middle;
        margin-right: 15px;
      }
    }
  }
  #chartLine2 {
    margin: 35px 0 10px;
  }
  .lifesignDetail-c {
    margin: 20px 0;
  }
  .btn {
    background: #dddddd;
    color: #000000;
    margin-left: 35px;
  }
}
</style>